package com.oocl.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class RequestUtil {

	public static final String POST = "POST";
	public static final String GET = "GET";

	@SuppressWarnings("rawtypes")
	public static Object request(String uri, String type, String params,
			Class clazz) {
		Object obj = null;
		try {
			URL url = new URL(uri);
			URLConnection conn = url.openConnection();
			HttpURLConnection httpconn = (HttpURLConnection) conn;
			if (POST.equals(type)) {
				httpconn.setRequestMethod("POST");
				if (null != params) {
					httpconn.setDoOutput(true);
					OutputStream out = httpconn.getOutputStream();
					PrintWriter writer = new PrintWriter(out, true);
					writer.println(params);
					writer.println("\n");
				}
				InputStream in = httpconn.getInputStream();
				String jso = "";
				if(in.available()!=0){
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					jso=reader.readLine();
					in.close();
					reader.close();
					httpconn.disconnect();
				}
				return jsonToObj(new String(jso), clazz);
			}
		} catch (MalformedURLException e) {
			System.out.println("url address is wrong or url format is wrong ");
		} catch (ProtocolException e) {
			System.out.println("对方服务没启动");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("io异常");
		} 
		return obj;
	}

	public static String wrapToJson(Object obj) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object jsonToObj(String json, Class clazz) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(json, clazz);

		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
